/*
 * $Id: DefaultTranslationService.java 42 2013-04-17 15:33:59Z gabakyan $
 * $Author: gabakyan $
 * $Revision: 42 $
 * $Date: 2013-04-17 15:33:59 +0000 (Wed, 17 Apr 2013) $
 *
 * Copyright (c) 2013 Supply Chain Intelligence (SCI), Inc.
 * http://www.scintelligence.com/, Email: info@scintelligence.com
 * All rights reserved.
 *
 * This file is part of Logistics Map.
 *
 * Logistics Map is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * Logistics Map is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Logistics Map.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.sci.logisticsmap.support.translator;

import org.springframework.core.GenericTypeResolver;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * The class {@code DefaultTranslationService} represents the default translation service.
 *
 * @author gabakyan@gmail.com (Last modified by $Author: gabakyan $)
 * @version $Revision: 42 $
 */
@Component("translationService")
public class DefaultTranslationService implements TranslationService, TranslatorRegistry {
    /**
     * The translators.
     */
	private final Map<TranslatablePair, Translator<?, ?>> translators = new HashMap<TranslatablePair, Translator<?, ?>>(36);

    /**
     * Add a plain translator to this registry.
     */
    public void addTranslator(Translator<?, ?> translator) {
        Class<?>[] args = GenericTypeResolver.resolveTypeArguments(translator.getClass(), Translator.class);
        addTranslator(args[0], args[1], translator);
    }

    /**
     * Add a plain translator to this registry.
     */
    public void addTranslator(Class<?> sourceType, Class<?> targetType, Translator<?, ?> translator) {
        translators.put(new TranslatablePair(sourceType, targetType), translator);
    }

    /*
     * (non-Javadoc)
     *
     * @see TranslationService#translate(Object, Object)
     */
	@SuppressWarnings("unchecked")
	public <Source, Target> void translate(Source source, Target target) {
		if (source == null) handleNullSource();
		if (target == null) handleNullTarget();
		translate(source, target, source != null ? source.getClass() : null, target != null ? target.getClass() : null);
	}

    /*
     * (non-Javadoc)
     *
     * @see TranslationService#translate(Object, Object, Class, Class)
     */
	@SuppressWarnings("unchecked")
    public <Source, Target> void translate(Source source, Target target, Class<?> sourceType, Class<?> targetType) {
		if (source == null) handleNullSource();
		if (target == null) handleNullTarget();
		Translator translator = getTranslator(sourceType, targetType);
		if (translator != null) {
			translator.translate(source, target);
		}
		else {
			handleTranslatorNotFound(source, target, sourceType, targetType);
		}
	}

    /**
     * Returns the translator.
     */
	private Translator getTranslator(Class<?> sourceType, Class<?> targetType) {
		TranslatablePair key = new TranslatablePair(sourceType, targetType);
		return translators.get(key);
	}

    /**
     * Handles the case when the source is null.
     */
    private void handleNullSource() {
        throw new IllegalArgumentException("The source to translate from cannot be null");
    }

    /**
     * Handles the case when the target is null.
     */
    private void handleNullTarget() {
        throw new IllegalArgumentException("The target to translate to cannot be null");
    }

    /**
     * Handles the case when the translator was not found.
     */
    private void handleTranslatorNotFound(Object source, Object target, Class<?> sourceType, Class<?> targetType) {
        if (source != null && target != null && !(targetType.isAssignableFrom(sourceType) && targetType.isInstance(source))) {
            throw new TranslatorNotFoundException(sourceType, targetType);
        }
    }

	/**
	 * Holder for a source-to-target class pair.
	 */
	public final class TranslatablePair {
        /**
         * The source type.
         */
		private final Class<?> sourceType;
        /**
         * The target type.
         */
		private final Class<?> targetType;

		/**
		 * Create a new source-to-target pair.
		 * @param sourceType the source type
		 * @param targetType the target type
		 */
		public TranslatablePair(Class<?> sourceType, Class<?> targetType) {
			this.sourceType = sourceType;
			this.targetType = targetType;
		}

        /**
         * Returns the source type.
         */
		public Class<?> getSourceType() {
			return this.sourceType;
		}

        /**
         * Returns the target type.
         */
		public Class<?> getTargetType() {
			return this.targetType;
		}

        /*
         * (non-Javadoc)
         *
         * @see Object#equals(Object)
         */
        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
				return true;
			}
            if (obj == null || obj.getClass() != TranslatablePair.class) {
				return false;
			}
            TranslatablePair other = (TranslatablePair) obj;
            return this.sourceType.equals(other.sourceType) && this.targetType.equals(other.targetType);

        }

        /*
         * (non-Javadoc)
         *
         * @see Object#hashCode()
         */
        @Override
        public int hashCode() {
            return this.sourceType.hashCode() * 31 + this.targetType.hashCode();
        }
    }
}
